<template>
  <view style="height: 100vh;">
    <image src="../../static/home-bg.png" class="fixed-bg"></image>
    <view class="content">
      <uni-nav-bar status-bar :border="false" :fixed="!showCustom" :background-color="bgColor" leftWidth="0">
        <view class="nav-bar-center" v-if="showCustom">
          <image src="../../static/logo.png" mode="heightFix" class="logo"></image>
          <!-- <view class="help">
            <text class="help-icon">?</text>帮助
          </view> -->
        </view>
        <view class="nav-bar-center" v-else>
          <view style="flex:1;text-align: center;font-size: 15px;">俊漾儿有声明信片</view>
        </view>
      </uni-nav-bar>
      <view class="home-search-container">
        <uni-icons type="search" color="#bee4e7" size="18"></uni-icons>
        <input type="text" placeholder="搜索你想要的明信片主题" placeholder-class="placeholder" v-model="postcardName"
          @confirm="handleConfirm" />
      </view>
      <swiper :indicator-dots="false" :autoplay="true" circular :interval="3000" :duration="1000"
        class="swiper-container">
        <swiper-item v-for="item in banners" :key="item.id">
          <image :src="item.imageUrl"></image>
        </swiper-item>

      </swiper>
      <view class="postcard-list-contaner">
        <view class="postcard-type-scroll">
          <scroll-view scroll-x="true" class="postcard-type-scroll" :show-scrollbar="false">
            <template v-for="(item,index) in postcardTypes">
              <view class="scroll-item" :id="item.postcardTypeId" :key="item.postcardTypeId"
                :class="{active:tab==item.postcardTypeId}" @click="selectTab(item)">{{item.typeName}}
              </view>
            </template>

          </scroll-view>
        </view>
        <view class="postcar-lists-inner">
          <view class="postcar-item" :key="item.postcardId" v-for="(item) in postcards"
            @longtap.stop="showActicon(item)">
            <image :src="'http://' +item.frontImgUrl" @click.stop="gotoMake(item)"></image>
            <!-- <view class="name">{{item.postcardName}}</view> -->
          </view>
        </view>
      </view>
    </view>
    <view class="add-btn" @click="gotoMake">
      <uni-icons type="plusempty" color="#fff" size="28"></uni-icons>
      <text>开始制作</text>
    </view>
    <privacy-popup ref="privacy" :privacyContractName="privacyContractName"></privacy-popup>
  </view>

</template>

<script>
  import {
    getPostcardList,
    getPostcardTypeList,
    getUserPostcardSelectList,
    getCourselImage
  } from '@/apis/postcard.js'
  import {
    wxLogin,
    addCollect,
    getCollectList,
    deleteCollects
  } from '@/apis/user.js'
  import {
    getQueryVarible
  } from '@/common/utils.js'
  export default {
    data() {
      return {
        showCustom: true,
        postcardTypes: [{
          postcardTypeId: -1,
          typeName: '全部'
        }],
        postcardName: '',
        tab: -1,
        bgColor: 'transparent',
        postcards: [],
        privacyContractName: '',
        pageIndex: 1,
        selectedCard: '',
        showNotice: true,
        banners: []
      }
    },
    onShareAppMessage() {
      return {
        title: `我的心意都在这张有声明信片里`,
      }
    },
    onShareTimeline() {
      return {
        title: `我的心意都在这张有声明信片里`,
      }
    },
    async onLoad(options) {
      if (options.q) {
        const q = decodeURIComponent(options.q)
        this.queryObj = getQueryVarible(q)
      }

      const _this = this;
      const userinfo = uni.getStorageSync('userinfo');
      this.userId = userinfo?.userId;
      getCourselImage().then(res => {
        if (res.rows) {
          this.banners = res.rows.map(item => {
            item.imageUrl = 'http://' + item.imageUrl
            return item;
          });
        }

      })
      this.handleConfirm()
      wx.getPrivacySetting({
        success: res => {
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            _this.privacyContractName = res.privacyContractName;
            _this.$refs.privacy.$refs.privacyPopup.open()
          }
        },
        fail: () => {},
        complete: () => {}
      })
    },
    onShow() {
      if (this.userId) {
        this.getMineCollects()
      }
      const deptId = uni.getStorageSync('userinfo').deptId;
      getPostcardTypeList({
        deptId: deptId
      }).then(res => {
        this.postcardTypes = [{
          postcardTypeId: -1,
          typeName: '全部'
        }, ...res.rows]
      })

    },
    onReachBottom() {
      this.pageIndex++
      if (this.pageIndex <= this.totalPage) {
        this.getPostcardList()
      }

    },
    methods: {
      handleConfirm() {
        this.pageIndex = 1;
        this.postcards = [];
        this.tab = -1;
        this.getPostcardList()
      },
      showActicon(item) {
        let collects = this.mineCollects.filter(ele => ele.postcardId == item.postcardId)
        let sheets = collects.length > 0 ? '取消收藏' : '收藏'
        uni.showActionSheet({
          itemList: [sheets],
          success: () => {
            if (sheets == '取消收藏') {
              this.deleteCollects(collects.flatMap(item => item.id).join(','))
            } else {
              this.addCollect(item.postcardId)
            }

          }
        })
      },
      getMineCollects() {
        getCollectList({
          userId: this.userId,
        }).then(res => {
          this.mineCollects = res.rows.map(item => {
            return {
              postcardId: item.postcardId,
              id: item.id
            }
          }) || [];
        })
      },
      async deleteCollects(postcardId) {
        let res = await deleteCollects({
          ids: postcardId,
          userId: this.userId
        })
        this.getMineCollects()
      },
      async addCollect(postcardId) {
        if (!this.userId) {
          uni.showModal({
            showCancel: false,
            title: '提示',
            content: '还未登录，请登录',
            confirmText: '确认',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/login/login'
                })
              }
            }
          })
        } else {
          let res = await addCollect({
            userId: this.userId,
            postcardId: postcardId,
            status: 1
          })
          this.$showtoast('收藏成功')
          setTimeout(() => {
            this.getMineCollects()
          }, 1000)
        }
      },
      getPostcardList() {
        let querParam = {
          pageNum: this.pageIndex,
          pageSize: 10,
          postcardName: this.postcardName,
        }
        if (this.tab != -1) {
          querParam.postcardType = this.tab
        }
        getPostcardList(querParam).then(res => {
          this.postcards = [...this.postcards, ...res.rows];
          this.totalPage = Math.ceil(res.total / 10)
        })
      },
      selectTab(item) {
        this.tab = item.postcardTypeId == -1 ? "" : item.postcardTypeId;
        this.postcards = []
        this.pageIndex = 1;
        this.getPostcardList()
      },
      gotoMake(card) {
        let userinfo = uni.getStorageSync('userinfo');
        if (card) {
          this.selectedCard = card.postcardId;
        }
        if (!userinfo) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {

          uni.navigateTo({
            url: '/pages/make/make?modelcardId=' + (this.selectedCard || '')
          })
        }

      }
    },
    onPageScroll(options) {
      const query = uni.createSelectorQuery().in(this);
      query.select('.postcard-list-contaner').boundingClientRect(data => {
        if (data.top < 30) {
          this.showCustom = false;
          this.bgColor = '#fff'
        } else {
          this.showCustom = true;
          this.bgColor = 'transparent'
        }
      }).exec()

    }
  }
</script>

<style scoped lang="scss">
  .content {
    position: absolute;
    height: 100vh;
    width: 100vw;
    padding: 0 20rpx 0 20rpx;
    box-sizing: border-box;
  }


  .add-btn {
    height: 60px;
    width: 60px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: fixed;
    right: 10px;
    bottom: 10px;
    font-size: 10px;
    background-color: #49c8bf;
    border-radius: 50%;
    color: #fff;
    box-shadow: 0 0 8rpx 1rpx rgba(0, 0, 0, 0.2);
  }

  .nav-bar-center {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    padding-right: 12rpx;

    .logo {
      height: 44px;
      width: 90px;
    }

    .help {
      color: white;
      font-size: 30rpx;

      .help-icon {
        margin-right: 4rpx;
        width: 30rpx;
        height: 30rpx;
        border: 2px solid #fff;
        border-radius: 50%;
        text-align: center;
        display: inline-block;
        vertical-align: bottom;
        line-height: 30rpx;
      }
    }
  }

  .home-search-container {
    padding-left: 30rpx;
    margin-top: 30rpx;
    height: 66rpx;
    width: 100%;
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 30px;
    box-sizing: border-box;
  }

  .swiper-container {
    height: 300rpx;
    margin-top: 30rpx;
    border-radius: 15px;

    image {
      width: 100%;
      height: 100%;
      border-radius: 15px;
    }
  }

  .postcard-list-contaner {
    margin-top: 30rpx;
    padding: 20rpx;
    height: 100%;
    border-radius: 30rpx;
    background: linear-gradient(to bottom, #fff, #cff6f3);
  }

  .postcard-type-scroll {
    height: 60rpx;
    white-space: nowrap;
    overflow: hidden;

    .scroll-item {
      margin-right: 20rpx;
      position: relative;
      font-size: 32rpx;
      font-weight: normal;
      line-height: 60rpx;
      display: inline-block;
      color: #a2a2a2;
    }

    .scroll-item.active {
      color: #000;
      font-weight: 700;
    }

    .scroll-item.active::after {
      content: '';
      display: block;
      width: 35rpx;
      height: 6rpx;
      background-color: #1eb3b1;
      border-radius: 9rpx;
      margin-top: -8rpx;
      margin-left: auto;
      margin-right: auto;
    }

  }

  .postcar-lists-inner {
    margin-top: 10rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .postcar-item {
      padding: 8rpx 10rpx;
      position: relative;
      margin-bottom: 20rpx;
      width: 48%;
      height: 200rpx;
      border-radius: 8rpx;
      background: #fff;
      box-shadow: 0 1px 4rpx 2rpx #e5e5e5;
      box-sizing: border-box;

      image {
        width: 100%;
        height: 100%;
      }

      .name {
        position: absolute;
        background: rgba(0, 0, 0, .4);
        left: 0;
        right: 0;
        bottom: 0;
        color: #fff;
        font-size: 25rpx;
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;
      }
    }
  }
</style>